<template>
  <div class="login">
      <van-nav-bar
        title="登录"
        left-arrow
        @click-left="$router.back()"
      />
      <van-form @submit="login">
        <van-field
          v-model="mobile"
          label="手机号"
          placeholder="请输入手机号"
          :rules="rules.mobile"
        />
        <van-field
          v-model="code"
          label="验证码"
          placeholder="验证码"
          :rules="rules.code"
        />
        <div style="margin: 16px;">
          <van-button
            round block type="info"
            native-type="submit"
            :disabled="loading"
            :loading='loading'
            loading-text="登陆中..."
          >
            提交
          </van-button>
        </div>
      </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'Login',
  data () {
    return {
      loading: false,
      mobile: '',
      code: '',
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码输入错误'
          }
        ]
      }
    }
  },
  methods: {
    async login () {
      this.loading = true
      try {
        const res = await login(this.mobile, this.code)
        console.log(res.data)
        // localStorage.setItem('token', JSON.stringify(res.data))
        this.$store.commit('user/setToken', res.data)
        // 封装到vuex异步，可以多次调用
        // await this.$store.dispatch('user/login', {
        //   mobile: this.mobile,
        //   code: this.code
        // })
        this.$toast.success('登录成功')
        if (this.$route.query.goBack) {
          return this.$router.back()
        }
        const back = this.$route.query.back || '/'
        this.$router.push(back)
      } catch {
        this.$toast.fail('登录失败')
      }
      this.loading = false
    }
  }
}
</script>

<style>

</style>
